<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Redis 分布式锁 | Oliver知识收集站</title>
    <meta name="generator" content="VuePress 1.9.7">
    
    <meta name="description" content="享受着互联网广泛知识，并加以记录，日积月累让它成为一个档案处！">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/oliver-vuepress/assets/css/0.styles.4ea20d86.css" as="style"><link rel="preload" href="/oliver-vuepress/assets/js/app.c21e6ffc.js" as="script"><link rel="preload" href="/oliver-vuepress/assets/js/3.6dd9a2a1.js" as="script"><link rel="preload" href="/oliver-vuepress/assets/js/1.898920d0.js" as="script"><link rel="preload" href="/oliver-vuepress/assets/js/50.805e1466.js" as="script"><link rel="prefetch" href="/oliver-vuepress/assets/js/10.41b2bf91.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/11.a95c117d.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/12.8607f0e1.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/13.a52d6846.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/14.249b4e52.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/15.d458d12e.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/16.ba334206.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/17.1b91c9fa.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/18.e2ea2eb5.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/19.bf0e2553.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/20.268bd174.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/21.cd1bbed5.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/22.da4bc7f7.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/23.12f0c72f.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/24.b7886742.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/25.6e71af85.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/26.5c127243.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/27.e98fd8bf.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/28.ce83b09c.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/29.50398f0f.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/30.05e1339c.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/31.ef4b13fb.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/32.ba5f8351.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/33.3902db0a.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/34.36a05884.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/35.87215872.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/36.db360c58.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/37.402e5374.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/38.c9228dd8.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/39.72ba5d1f.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/4.7bb03d47.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/40.7e7949bf.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/41.c0d5b947.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/42.d9984467.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/43.e6a43668.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/44.10d7fe47.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/45.f692ec2d.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/46.9b920343.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/47.8e3d94f9.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/48.7d356e5b.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/49.b0df6271.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/5.1fa544da.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/51.1b31d40e.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/52.44e69a41.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/53.da1def53.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/54.6569f7db.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/55.5fc3de47.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/56.da649377.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/57.6ff15ed4.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/58.a62f6424.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/59.f68ae517.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/6.f5bd8e9b.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/60.dda416bc.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/61.4e0c719f.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/62.8c5ef01e.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/63.7089eb8b.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/64.b5ec150d.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/65.6720cda4.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/66.4ee90e29.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/67.cc4b0c6d.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/7.d5950c53.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/8.382fb3a5.js"><link rel="prefetch" href="/oliver-vuepress/assets/js/9.d593f4c1.js">
    <link rel="stylesheet" href="/oliver-vuepress/assets/css/0.styles.4ea20d86.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar" data-v-130b300a><div data-v-130b300a><div class="password-shadow password-wrapper-out" style="display:none;" data-v-25ba6db2 data-v-130b300a data-v-130b300a><h3 class="title" data-v-25ba6db2 data-v-25ba6db2>Oliver知识收集站</h3> <p class="description" data-v-25ba6db2 data-v-25ba6db2>享受着互联网广泛知识，并加以记录，日积月累让它成为一个档案处！</p> <label id="box" class="inputBox" data-v-25ba6db2 data-v-25ba6db2><input type="password" value="" data-v-25ba6db2> <span data-v-25ba6db2>Konck! Knock!</span> <button data-v-25ba6db2>OK</button></label> <div class="footer" data-v-25ba6db2 data-v-25ba6db2><span data-v-25ba6db2><i class="iconfont reco-theme" data-v-25ba6db2></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-25ba6db2>vuePress-theme-reco</a></span> <span data-v-25ba6db2><i class="iconfont reco-copyright" data-v-25ba6db2></i> <a data-v-25ba6db2><span data-v-25ba6db2>oliver.shi</span>
            
          <!---->
          2022
        </a></span></div></div> <div class="hide" data-v-130b300a><header class="navbar" data-v-130b300a><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/oliver-vuepress/" class="home-link router-link-active"><!----> <span class="site-name">Oliver知识收集站</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/oliver-vuepress/" class="nav-link"><i class="undefined"></i>
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="undefined"></i>
      Java
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/java/basics/" class="nav-link"><i class="undefined"></i>
  基础
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/java/concurrent/" class="nav-link"><i class="undefined"></i>
  并发
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/java/jvm/jvm.html" class="nav-link"><i class="undefined"></i>
  JVM
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/java/other/" class="nav-link"><i class="undefined"></i>
  杂
</a></li></ul></div></div><div class="nav-item"><a href="/oliver-vuepress/articles/spring/first.html" class="nav-link"><i class="undefined"></i>
  Spring
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="undefined"></i>
      中间件
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/middleware/redis/redis.html" class="nav-link"><i class="undefined"></i>
  Redis
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/middleware/kafka/framework.html" class="nav-link"><i class="undefined"></i>
  Kafka
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/middleware/zookeeper.html" class="nav-link"><i class="undefined"></i>
  Zookeeper
</a></li></ul></div></div><div class="nav-item"><a href="/oliver-vuepress/articles/algorithm/" class="nav-link"><i class="undefined"></i>
  算法
</a></div><div class="nav-item"><a href="/oliver-vuepress/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  TimeLine
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="undefined"></i>
      收集站
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/article/first.html" class="nav-link"><i class="undefined"></i>
  技术好文
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/book/first.html" class="nav-link"><i class="undefined"></i>
  书籍
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/assembly/first.html" class="nav-link"><i class="undefined"></i>
  优秀开发组件
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/software/first.html" class="nav-link"><i class="undefined"></i>
  软件
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/plugin/first.html" class="nav-link"><i class="undefined"></i>
  插件
</a></li></ul></div></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-130b300a></div> <aside class="sidebar" data-v-130b300a><div class="personal-info-wrapper" data-v-39576ba9 data-v-130b300a><!----> <h3 class="name" data-v-39576ba9>
    oliver.shi
  </h3> <div class="num" data-v-39576ba9><div data-v-39576ba9><h3 data-v-39576ba9>52</h3> <h6 data-v-39576ba9>Articles</h6></div> <div data-v-39576ba9><h3 data-v-39576ba9>6</h3> <h6 data-v-39576ba9>Tags</h6></div></div> <ul class="social-links" data-v-39576ba9></ul> <hr data-v-39576ba9></div> <nav class="nav-links"><div class="nav-item"><a href="/oliver-vuepress/" class="nav-link"><i class="undefined"></i>
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="undefined"></i>
      Java
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/java/basics/" class="nav-link"><i class="undefined"></i>
  基础
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/java/concurrent/" class="nav-link"><i class="undefined"></i>
  并发
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/java/jvm/jvm.html" class="nav-link"><i class="undefined"></i>
  JVM
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/java/other/" class="nav-link"><i class="undefined"></i>
  杂
</a></li></ul></div></div><div class="nav-item"><a href="/oliver-vuepress/articles/spring/first.html" class="nav-link"><i class="undefined"></i>
  Spring
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="undefined"></i>
      中间件
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/middleware/redis/redis.html" class="nav-link"><i class="undefined"></i>
  Redis
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/middleware/kafka/framework.html" class="nav-link"><i class="undefined"></i>
  Kafka
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/middleware/zookeeper.html" class="nav-link"><i class="undefined"></i>
  Zookeeper
</a></li></ul></div></div><div class="nav-item"><a href="/oliver-vuepress/articles/algorithm/" class="nav-link"><i class="undefined"></i>
  算法
</a></div><div class="nav-item"><a href="/oliver-vuepress/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  TimeLine
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="undefined"></i>
      收集站
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/article/first.html" class="nav-link"><i class="undefined"></i>
  技术好文
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/book/first.html" class="nav-link"><i class="undefined"></i>
  书籍
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/assembly/first.html" class="nav-link"><i class="undefined"></i>
  优秀开发组件
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/software/first.html" class="nav-link"><i class="undefined"></i>
  软件
</a></li><li class="dropdown-item"><!----> <a href="/oliver-vuepress/articles/collect/plugin/first.html" class="nav-link"><i class="undefined"></i>
  插件
</a></li></ul></div></div> <!----></nav> <!----> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-25ba6db2 data-v-130b300a><h3 class="title" data-v-25ba6db2 data-v-25ba6db2>Redis 分布式锁</h3> <!----> <label id="box" class="inputBox" data-v-25ba6db2 data-v-25ba6db2><input type="password" value="" data-v-25ba6db2> <span data-v-25ba6db2>Konck! Knock!</span> <button data-v-25ba6db2>OK</button></label> <div class="footer" data-v-25ba6db2 data-v-25ba6db2><span data-v-25ba6db2><i class="iconfont reco-theme" data-v-25ba6db2></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-25ba6db2>vuePress-theme-reco</a></span> <span data-v-25ba6db2><i class="iconfont reco-copyright" data-v-25ba6db2></i> <a data-v-25ba6db2><span data-v-25ba6db2>oliver.shi</span>
            
          <!---->
          2022
        </a></span></div></div> <div data-v-130b300a><main class="page"><section><div class="page-title"><h1 class="title">Redis 分布式锁</h1> <div data-v-f875f3fc><i class="iconfont reco-account" data-v-f875f3fc><span data-v-f875f3fc>oliver.shi</span></i> <i class="iconfont reco-date" data-v-f875f3fc><span data-v-f875f3fc>4/20/2022</span></i> <!----> <i class="tags iconfont reco-tag" data-v-f875f3fc><span class="tag-item" data-v-f875f3fc>Redis</span></i></div></div> <div class="theme-reco-content content__default"><h2 id="锁-和-分布式锁"><a href="#锁-和-分布式锁" class="header-anchor">#</a> 锁 和 分布式锁</h2> <h3 id="锁"><a href="#锁" class="header-anchor">#</a> 锁</h3> <blockquote><p><code>资源</code>通常是共享的，在并发情况下，通常会发送竞争。而锁是 资源竞争时的钥匙，避免 <code>共享资源</code> 被多个持有</p></blockquote> <p><strong>Java中的锁</strong></p> <p>Java为了保护共享资源，在多线程情况下的，原子性操作，使用 <code>Synchronized</code> 、<code>Lock</code> 去声明使用锁。</p> <p>Lock 相对与 <code>Synchronized</code> 更公平、更灵活、可以设置超时时间</p> <h3 id="分布式锁"><a href="#分布式锁" class="header-anchor">#</a> 分布式锁</h3> <p>无论 <code>Synchronized</code> 、<code>Lock</code>  都是单体应用时 对多线程操作共享资源时的，锁操作。</p> <p>但是 在多机集群部署的情况下，A 机器中的<code>Synchronized</code> 关键字，并不能控制 B,C 中的内容。</p> <p>所以 需要 <code>分布式锁</code> 来 协调多节点。</p> <p><strong>锁的性能优化点</strong></p> <ul><li>减少持有锁的时间：避免锁的流程太长</li> <li>减少锁的颗粒度：避免锁的资源太大</li> <li>锁分离：大多数情况，读可以不加锁，所以我们可以将锁分离，读写各一把锁</li></ul> <p><strong>需要注意那些点</strong></p> <ul><li>互斥性: 任一时刻，只允许一个客户端获取锁</li> <li>防死锁：防止程序崩溃，或网络异常，导致没有释放锁，而造成死锁</li> <li>持有人解锁：加锁和解锁 必须是同一个人</li> <li>可重入：当一个客户端获取对象锁之后，这个客户端可以再次获取这个对象上的锁。</li> <li>任务执行超时：执行过程中，遇到查库sql慢，并发导致服务响应问题等等原因，导致程序还没执行完成，即解锁</li></ul> <h2 id="锁的实现方式"><a href="#锁的实现方式" class="header-anchor">#</a> 锁的实现方式</h2> <h3 id="加锁"><a href="#加锁" class="header-anchor">#</a> 加锁</h3> <p><strong>加锁1 - <code>setnx</code> 命令加锁</strong></p> <blockquote><p><code>setnx</code> 命令加锁，这种情况最简单方法，但是由于单个节点程序崩溃等情况，锁还存在，其他节点无法获取锁，会导致死锁问题</p></blockquote> <div class="language-Java extra-class"><pre class="language-java"><code>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">void</span> <span class="token function">lock1SetLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token comment">/**
         * 获取锁的方式：通过 setNx 进行获取锁
         * 问题：如果程序崩溃 或  del 指令没有被调用, 可能会先入 死锁的问题
         */</span>
        <span class="token class-name">Jedis</span> jedis <span class="token operator">=</span> jedisPool<span class="token punctuation">.</span><span class="token function">getResource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Long</span> isLock <span class="token operator">=</span> jedis<span class="token punctuation">.</span><span class="token function">setnx</span><span class="token punctuation">(</span><span class="token string">&quot;SD_test&quot;</span><span class="token punctuation">,</span> UUID<span class="token punctuation">.</span><span class="token function">randomUUID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>isLock <span class="token operator">&gt;</span> <span class="token number">0L</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;获取到锁,执行解锁&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;未获取到锁！！&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        jedis<span class="token punctuation">.</span><span class="token function">del</span><span class="token punctuation">(</span><span class="token string">&quot;SD_test&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
</code></pre></div><p><strong>加锁2 - <code>setnx</code> + <code>expire</code></strong></p> <blockquote><p>加锁的同时，进行设置 过期时间，就算程序崩溃，到了指定时间，会自动释放锁</p></blockquote> <p>存在的问题: <code>setnx</code> + <code>expire</code> 非原子性操作，sentx 执行完成后，程序崩溃 或 网络请求丢失，出现过期时间未设置成功</p> <div class="language-Java extra-class"><pre class="language-java"><code> <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">void</span> <span class="token function">lock2SetLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">/**
         * 优化方式：锁的基础上 新增了过期时间，及时程序中间崩溃，也可以在 10S 后 自动解锁
         * 问题：setnx 和  expire  操作不是原子性操作，可能是因为机器掉电或者是被人为杀掉的,就会导致 expire 得不到执行,也会造成死锁
         */</span>
        <span class="token class-name">Jedis</span> jedis <span class="token operator">=</span> jedisPool<span class="token punctuation">.</span><span class="token function">getResource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Long</span> isLock <span class="token operator">=</span> jedis<span class="token punctuation">.</span><span class="token function">setnx</span><span class="token punctuation">(</span><span class="token string">&quot;SD_test2&quot;</span><span class="token punctuation">,</span> UUID<span class="token punctuation">.</span><span class="token function">randomUUID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        jedis<span class="token punctuation">.</span><span class="token function">expire</span><span class="token punctuation">(</span><span class="token string">&quot;SD_test2&quot;</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>isLock <span class="token operator">&gt;</span> <span class="token number">0L</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;获取到锁,执行解锁&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;未获取到锁！！&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
</code></pre></div><p><strong>加锁3 - 原子性加锁</strong></p> <blockquote><p>Redis 2.8之后 提供 nx 、expire 两个命令同事执行的 原子性操作</p></blockquote> <div class="language-java extra-class"><pre class="language-java"><code>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">void</span> <span class="token function">lock3SetLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">/**
         * 优化方式：Redis 2.8之后 提供 nx 、expire 两个命令同事执行的 原子性操作
         * Redis指令 set(key,value,NX,EX,timeout) 指令
         * 问题：
         */</span>
        <span class="token class-name">Jedis</span> jedis <span class="token operator">=</span> jedisPool<span class="token punctuation">.</span><span class="token function">getResource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">String</span> result <span class="token operator">=</span> jedis<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token string">&quot;SD_test3&quot;</span><span class="token punctuation">,</span> UUID<span class="token punctuation">.</span><span class="token function">randomUUID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">SetParams</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">nx</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">ex</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token string">&quot;OK&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;获取到锁,执行解锁&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;未获取到锁！！&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
</code></pre></div><p><strong>加锁4 - Lua</strong></p> <blockquote><p>除了 Redis的 提供的原子性命令，还可以使用 Lua 脚本，一个lua 脚本的命令，可以实现原子性</p></blockquote> <div class="language-java extra-class"><pre class="language-java"><code><span class="token comment">/**
     * lua 加锁 + lua 删除锁
     *
     * @throws InterruptedException
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">void</span> <span class="token function">lock4SetLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
        <span class="token class-name">Long</span> lockReleaseOK <span class="token operator">=</span> <span class="token number">1L</span><span class="token punctuation">;</span>
        <span class="token class-name">Jedis</span> jedis <span class="token operator">=</span> jedisPool<span class="token punctuation">.</span><span class="token function">getResource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> luaLockscripts <span class="token operator">=</span> <span class="token string">&quot;if redis.call('setnx',KEYS[1],ARGV[1]) == 1 then&quot;</span> <span class="token operator">+</span>
                <span class="token string">&quot; redis.call('expire',KEYS[1],ARGV[2]) return 1 else return 0 end&quot;</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> luaDelScript <span class="token operator">=</span> <span class="token string">&quot;if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end&quot;</span><span class="token punctuation">;</span>


        <span class="token class-name">String</span> lockValue <span class="token operator">=</span> UUID<span class="token punctuation">.</span><span class="token function">randomUUID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Object</span> result <span class="token operator">=</span> jedis<span class="token punctuation">.</span><span class="token function">eval</span><span class="token punctuation">(</span>luaLockscripts<span class="token punctuation">,</span>
                <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">singletonList</span><span class="token punctuation">(</span><span class="token string">&quot;SD_test4&quot;</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span>lockValue<span class="token punctuation">,</span> <span class="token string">&quot;60000&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>result<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token number">1L</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;我获取到锁了！要睡一会&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">2000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;我获取到锁了！我醒了&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token class-name">Object</span> delResult <span class="token operator">=</span> jedis<span class="token punctuation">.</span><span class="token function">eval</span><span class="token punctuation">(</span>luaDelScript<span class="token punctuation">,</span>
                <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">singletonList</span><span class="token punctuation">(</span><span class="token string">&quot;SD_test4&quot;</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">List</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>lockValue<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>delResult <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> delResult<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>lockReleaseOK<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;删除成功！&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;执行完成！&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
</code></pre></div><p><strong>加锁5 - 可重入锁</strong></p> <blockquote><p>不是很好的实现方式，应该将相关线程信息记录在 Redis value中，进行验证</p></blockquote> <div class="language-java extra-class"><pre class="language-java"><code> 	<span class="token comment">// 线程持有的锁id</span>
    <span class="token keyword">private</span> <span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> localContext <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// 线程持有者</span>
    <span class="token keyword">private</span> <span class="token class-name">Thread</span> ownerThread<span class="token punctuation">;</span>

    <span class="token comment">//</span>
    <span class="token keyword">public</span> <span class="token class-name">Boolean</span> <span class="token function">redisReentrantLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">Jedis</span> jedis <span class="token operator">=</span> jedisPool<span class="token punctuation">.</span><span class="token function">getResource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> id <span class="token operator">=</span> UUID<span class="token punctuation">.</span><span class="token function">randomUUID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span> t <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token string">&quot;Ok&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>jedis<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token string">&quot;lock&quot;</span><span class="token punctuation">,</span> id<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">SetParams</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">nx</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">ex</span><span class="token punctuation">(</span><span class="token number">60</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            localContext<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>ownerThread <span class="token operator">=</span> t<span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token class-name">Boolean</span><span class="token punctuation">.</span>TRUE<span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>ownerThread <span class="token operator">==</span> t<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token class-name">Boolean</span><span class="token punctuation">.</span>TRUE<span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token class-name">Boolean</span><span class="token punctuation">.</span>FALSE<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
</code></pre></div><p><strong>加锁6 - 确保过期时间大于业务执行时间</strong></p> <p>当遇到 业务执行时间   大于 设置过期时间的解决2中方案：</p> <ol><li>预判型：进行压测，测试出一个压力最大值。 将 压力值 * 2  = 过期时间</li> <li>执行补救式： 用来标识是否开启定时刷新过期时间， 在增加一个scheduleExpirationRenewal方法用于开启刷新过期时间的线程</li></ol> <div class="language-java extra-class"><pre class="language-java"><code> <span class="token keyword">protected</span> <span class="token keyword">volatile</span> <span class="token keyword">boolean</span> isOpenExpirationRenewal <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * 开启定时刷新
     */</span>
    <span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">scheduleExpirationRenewal</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">Thread</span> renewalThread <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">ExpirationRenewal</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        renewalThread<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 刷新key的过期时间
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">class</span> <span class="token class-name">ExpirationRenewal</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span><span class="token punctuation">{</span>
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span>isOpenExpirationRenewal<span class="token punctuation">)</span><span class="token punctuation">{</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;执行延迟失效时间中...&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token class-name">String</span> checkAndExpireScript <span class="token operator">=</span> <span class="token string">&quot;if redis.call('get', KEYS[1]) == ARGV[1] then &quot;</span> <span class="token operator">+</span>
                        <span class="token string">&quot;return redis.call('expire',KEYS[1],ARGV[2]) &quot;</span> <span class="token operator">+</span>
                        <span class="token string">&quot;else &quot;</span> <span class="token operator">+</span>
                        <span class="token string">&quot;return 0 end&quot;</span><span class="token punctuation">;</span>
                jedis<span class="token punctuation">.</span><span class="token function">eval</span><span class="token punctuation">(</span>checkAndExpireScript<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> lockKey<span class="token punctuation">,</span> lockValue<span class="token punctuation">,</span> <span class="token string">&quot;30&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token comment">//休眠10秒</span>
                <span class="token function">sleepBySencond</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
</code></pre></div><h3 id="解锁"><a href="#解锁" class="header-anchor">#</a> 解锁</h3> <blockquote><p>Redis 解锁，需要注意，锁的持有人才能解锁</p></blockquote> <div class="language-java extra-class"><pre class="language-java"><code>		<span class="token comment">/**
     * lua 删除锁：验证是数据是否一致
     *
     * @throws InterruptedException
     */</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">void</span> <span class="token function">lock5SetLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
        <span class="token class-name">Long</span> lockReleaseOK <span class="token operator">=</span> <span class="token number">1L</span><span class="token punctuation">;</span>
        <span class="token class-name">Jedis</span> jedis <span class="token operator">=</span> jedisPool<span class="token punctuation">.</span><span class="token function">getResource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
       
        <span class="token class-name">String</span> luaDelScript <span class="token operator">=</span> <span class="token string">&quot;if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end&quot;</span><span class="token punctuation">;</span>

        <span class="token class-name">Object</span> delResult <span class="token operator">=</span> jedis<span class="token punctuation">.</span><span class="token function">eval</span><span class="token punctuation">(</span>luaDelScript<span class="token punctuation">,</span>
                <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">singletonList</span><span class="token punctuation">(</span><span class="token string">&quot;SD_test4&quot;</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">List</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>lockValue<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>delResult <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> delResult<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>lockReleaseOK<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;删除成功！&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;执行完成！&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

</code></pre></div><h3 id="分布式环集群加锁"><a href="#分布式环集群加锁" class="header-anchor">#</a> 分布式环集群加锁</h3> <p><strong>Redis锁真的靠谱吗？</strong></p> <p>从上面的案例来看，及基本已经很完美的解决了我们想要的分布式锁的公共</p> <p>但是 如果在 分布式 集群的情况下 可能存在：在主节点申请到了锁，这个时候 主节点挂了，主节点锁信息未同步到从节点。从节点变为主节点，新的请求来进行获取锁，会立马批准，这就会导致一个锁被两个客户端同时持有</p> <p>为此：衍生出 RedLock 算法</p> <p><strong>RedLock</strong></p> <blockquote><p><code>RedLock</code> 基于 大多数机制 基本原理是利用多个Redis集群，用多数的集群加锁成功，减少Redis某个集群出故障，造成分布式锁出现问题的概率</p></blockquote> <img src="/oliver-vuepress/middleware/redislearn/RedLock.png" alt="foo"> <p><strong>加锁过程</strong></p> <ol><li>创建多个集群的lock</li> <li>循环执行加锁操作</li> <li>加锁失败，验证是否大于最小失败数  (3个节点 最多只能1个失败，5个的话最多只能2个失败。公式：（n / 2 +1）</li> <li>加锁 验证 加锁超时失败</li> <li>出现 3，4 情况的话，那么就会进行解锁操作，解锁所有已经加完锁的机器</li></ol> <ul><li><p>RedLock的缺点：</p> <ul><li>需要维护更多的集群 (由于时基于多机器的，所以最少需要3台)</li> <li>多节点读写，意味着Redis 性能下降</li></ul></li></ul> <h3 id="分布式锁的安全问题"><a href="#分布式锁的安全问题" class="header-anchor">#</a> 分布式锁的安全问题</h3> <blockquote><p>一下是分布式不可避免的一些问题</p></blockquote> <ul><li>GC问题</li> <li>长时间网络I/O</li></ul> <h2 id="redisson"><a href="#redisson" class="header-anchor">#</a> Redisson</h2> <blockquote><p>Redisson是一个在Redis的基础上实现的Java驻内存数据网格（In-Memory Data Grid）。它不仅提供了一系列的分布式的Java常用对象，还提供了许多分布式服务。</p> <p>Redisson提供了使用Redis的最简单和最便捷的方法</p></blockquote> <h3 id="如何实现的锁"><a href="#如何实现的锁" class="header-anchor">#</a> 如何实现的锁</h3> <img src="/oliver-vuepress/middleware/redislearn/image-20220420144958197.png" alt="foo"> <h3 id="加锁-解锁过程分析"><a href="#加锁-解锁过程分析" class="header-anchor">#</a> 加锁&amp;解锁过程分析</h3> <p><strong>使用的锁的案例</strong></p> <div class="language-Java extra-class"><pre class="language-java"><code>    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">void</span> <span class="token function">testRedission</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
        <span class="token class-name">RLock</span> rLock <span class="token operator">=</span> redissonClient<span class="token punctuation">.</span><span class="token function">getLock</span><span class="token punctuation">(</span><span class="token string">&quot;sd_test1&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 进行加锁</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>rLock<span class="token punctuation">.</span><span class="token function">tryLock</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;获取锁成功&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token comment">// 进行释放锁</span>
        rLock<span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

</code></pre></div><p><strong>查看加锁逻辑</strong></p> <p>向下查看 <code>tryLock</code>的实现细节</p> <blockquote><p>RedissonLock.tryLock()  -----&gt;  RedissonLock.tryAcquire() -----&gt; RedissonLock.tryAcquireAsync() -----&gt;  RedissonLock.tryLockInnerAsync()  方法， 可以看到最终是通过执行 Lua 脚本实现的加锁操作</p></blockquote> <div class="language-lua extra-class"><pre class="language-lua"><code><span class="token operator">//</span> 加锁 Lua 脚本
<span class="token operator">//</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> 锁名称
<span class="token operator">//</span> ARGV<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> 过期时间
<span class="token operator">//</span> ARGV<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> 线程名称

<span class="token keyword">if</span> <span class="token punctuation">(</span>redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'exists'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">then</span>       <span class="token comment">-- 查看 锁名称是否存在</span>
    redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'hincrby'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token comment">-- 无锁，创建一个 hash,key=锁名称 field=线程名称，value = 1</span>
    redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'pexpire'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       <span class="token comment">-- 设置 hash 的过期时间</span>
    <span class="token keyword">return</span> <span class="token keyword">nil</span><span class="token punctuation">;</span> <span class="token keyword">end</span><span class="token punctuation">;</span> 
<span class="token keyword">if</span> <span class="token punctuation">(</span>redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'hexists'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">)</span>     <span class="token comment">-- 有锁，并且 是当前线程 持有的锁</span>
    <span class="token keyword">then</span> redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'hincrby'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">-- 重入锁 value+1</span>
    redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'pexpire'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>          <span class="token comment">-- 重新设置过期时间</span>
 <span class="token keyword">return</span> <span class="token keyword">nil</span><span class="token punctuation">;</span> <span class="token keyword">end</span><span class="token punctuation">;</span> 
 <span class="token keyword">return</span> redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'pttl'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                 <span class="token comment">-- 未加锁成功，返回锁的时间</span>
</code></pre></div><p><strong>查看解锁逻辑</strong></p> <p>向下查看 <code>unLock</code>的实现细节</p> <blockquote><p>RedissonLock.unlock()  -----&gt;  RedissonLock.unlockAsync() -----&gt; RedissonLock.unlockInnerAsync() 方法， 可以看到最终是通过执行 Lua 脚本实现的释放锁操作</p></blockquote> <div class="language-lua extra-class"><pre class="language-lua"><code><span class="token operator">//</span> 释放锁 Lua 脚本
<span class="token operator">//</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> 锁的名称
<span class="token operator">//</span> KEYS<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> 频道名称  redisson_lock__channel<span class="token punctuation">:</span>锁名称
<span class="token operator">//</span> ARGV<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> 释放锁消息内容
<span class="token operator">//</span> ARGV<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> 过期时间
<span class="token operator">//</span> ARGV<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span> 线程名称
 <span class="token keyword">if</span> <span class="token punctuation">(</span>redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'hexists'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">then</span>             <span class="token comment">-- 锁存在，但是不是当前线程加的锁 直接放回</span>
    <span class="token keyword">return</span> <span class="token keyword">nil</span><span class="token punctuation">;</span><span class="token keyword">end</span><span class="token punctuation">;</span>
 <span class="token keyword">local</span> counter <span class="token operator">=</span> redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'hincrby'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>       <span class="token comment">-- 可重入锁，value 进行-1</span>
 <span class="token keyword">if</span> <span class="token punctuation">(</span>counter <span class="token operator">&gt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">then</span>                                              <span class="token comment">-- 可重入次数 0, 说明存在重入锁的操作，不能删除key</span>
     redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'pexpire'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                       <span class="token comment">-- 延长 锁 过期的时间</span>
     <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span> 
	<span class="token keyword">else</span> redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'del'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                                    <span class="token comment">-- 删除key, 并发布释放锁的消息</span>
  redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'publish'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">return</span> <span class="token number">1</span><span class="token punctuation">;</span> <span class="token keyword">end</span><span class="token punctuation">;</span>
 <span class="token keyword">return</span> <span class="token keyword">nil</span><span class="token punctuation">;</span>
</code></pre></div><p><strong>这个加解锁的过程总结</strong></p> <blockquote><p>Redisson 封装 提供了一个简单的加锁、解锁的方法，基本实现了 <code>互斥性</code>、<code>防死锁</code>、<code>持有人解锁</code>、<code>可重入锁</code>、<code>自定延时机制</code></p></blockquote> <p>自动延时机制：<strong>客户端A</strong> 一旦加锁成功后，会启动一个 <code>wacth dog</code> 看门狗。<strong>他是一个后台线程，默认每隔 10秒 检查一下</strong> <strong>客户端A</strong>  是否还持有锁，那么久会不断的去延长锁的生存时间</p> <p>可重入性：通过 hash 结构存储 锁， key: 客户端信息   value: 为加锁次数。当 当前客户端进行多次加锁时，会将值累加1  （结束时，需要为0时，才能进行解锁）</p> <h3 id="watch-dog"><a href="#watch-dog" class="header-anchor">#</a> watch dog</h3> <blockquote><p>Redis 通过 <code>watch dog</code> 来实现 锁的 自动延期机制。那为什么需要自动延时机制呢？？</p></blockquote> <p>由于可能存在 客户端拿到锁后，由于服务节点崩溃、网络请求丢失 或 程序崩溃等问题 导致死锁的情况。 为了解决该类问题 通过给锁 设置一个 过期时间。这样引入了新的问题：在指定的 过期时间内，线程的操作还未执行完成。锁就被释放了。</p> <p><strong>所以需要自动延迟机制</strong></p> <p><strong>Redisson核心实现方式</strong></p> <blockquote><p>默认：<code>每10秒</code> 检测一下，如果还持有锁，会进行续约 <code>30秒</code></p> <p>也可以通过修改 <code>Config.lockWatchdogTimeout</code> 来另行指定</p></blockquote> <p><strong>源码分析</strong></p> <blockquote><p>在调用lock方法的 链路中 RedissonLock.tryLock()  -----&gt;  RedissonLock.tryAcquire() -----&gt; RedissonLock.tryAcquireAsync()  进行了 相关操作</p></blockquote> <ul><li>当 leaseTime 未进行显示设置时 watch dog 才生效
<ul><li>则 leaseTime = -1</li></ul></li></ul> <div class="language-java extra-class"><pre class="language-java"><code><span class="token keyword">private</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">RFuture</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Long</span><span class="token punctuation">&gt;</span></span> <span class="token function">tryAcquireAsync</span><span class="token punctuation">(</span><span class="token keyword">long</span> waitTime<span class="token punctuation">,</span> <span class="token keyword">long</span> leaseTime<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span> unit<span class="token punctuation">,</span> <span class="token keyword">long</span> threadId<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">RFuture</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Long</span><span class="token punctuation">&gt;</span></span> ttlRemainingFuture<span class="token punctuation">;</span>
        <span class="token comment">//如果指定了加锁时间，会直接去加锁</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>leaseTime <span class="token operator">!=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            ttlRemainingFuture <span class="token operator">=</span> <span class="token function">tryLockInnerAsync</span><span class="token punctuation">(</span>waitTime<span class="token punctuation">,</span> leaseTime<span class="token punctuation">,</span> unit<span class="token punctuation">,</span> threadId<span class="token punctuation">,</span> <span class="token class-name">RedisCommands</span><span class="token punctuation">.</span>EVAL_LONG<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token comment">//没有指定加锁时间 会先进行加锁，并且默认时间就是 LockWatchdogTimeout的时间</span>
            <span class="token comment">//这个是异步操作 返回RFuture 类似netty中的future</span>
            ttlRemainingFuture <span class="token operator">=</span> <span class="token function">tryLockInnerAsync</span><span class="token punctuation">(</span>waitTime<span class="token punctuation">,</span> internalLockLeaseTime<span class="token punctuation">,</span>
                    <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span> threadId<span class="token punctuation">,</span> <span class="token class-name">RedisCommands</span><span class="token punctuation">.</span>EVAL_LONG<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment">//这里也是类似netty Future 的addListener，在future内容执行完成后执行</span>
        ttlRemainingFuture<span class="token punctuation">.</span><span class="token function">onComplete</span><span class="token punctuation">(</span><span class="token punctuation">(</span>ttlRemaining<span class="token punctuation">,</span> e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>e <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">return</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            <span class="token comment">// lock acquired</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>ttlRemaining <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token comment">// leaseTime不为-1时，不会自动延期</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>leaseTime <span class="token operator">!=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    internalLockLeaseTime <span class="token operator">=</span> unit<span class="token punctuation">.</span><span class="token function">toMillis</span><span class="token punctuation">(</span>leaseTime<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                    <span class="token comment">//这里是定时执行 当前锁自动延期的动作,leaseTime为-1时，才会自动延期</span>
                    <span class="token function">scheduleExpirationRenewal</span><span class="token punctuation">(</span>threadId<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> ttlRemainingFuture<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
</code></pre></div><blockquote><p>scheduleExpirationRenewal 中会调用renewExpiration 这里我们可以看到是,启用了一个timeout定时，去执行延期动作</p></blockquote> <div class="language-java extra-class"><pre class="language-java"><code><span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">renewExpiration</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">ExpirationEntry</span> ee <span class="token operator">=</span> EXPIRATION_RENEWAL_MAP<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token function">getEntryName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>ee <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token class-name">Timeout</span> task <span class="token operator">=</span> commandExecutor<span class="token punctuation">.</span><span class="token function">getConnectionManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">newTimeout</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">TimerTask</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Timeout</span> timeout<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">{</span>
                <span class="token class-name">ExpirationEntry</span> ent <span class="token operator">=</span> EXPIRATION_RENEWAL_MAP<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token function">getEntryName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>ent <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token keyword">return</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
                <span class="token class-name">Long</span> threadId <span class="token operator">=</span> ent<span class="token punctuation">.</span><span class="token function">getFirstThreadId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>threadId <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token keyword">return</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>

                <span class="token class-name">RFuture</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Boolean</span><span class="token punctuation">&gt;</span></span> future <span class="token operator">=</span> <span class="token function">renewExpirationAsync</span><span class="token punctuation">(</span>threadId<span class="token punctuation">)</span><span class="token punctuation">;</span>
                future<span class="token punctuation">.</span><span class="token function">onComplete</span><span class="token punctuation">(</span><span class="token punctuation">(</span>res<span class="token punctuation">,</span> e<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>e <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">&quot;Can't update lock &quot;</span> <span class="token operator">+</span> <span class="token function">getRawName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot; expiration&quot;</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        EXPIRATION_RENEWAL_MAP<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token function">getEntryName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">return</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>

                    <span class="token keyword">if</span> <span class="token punctuation">(</span>res<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        <span class="token comment">//如果 没有报错，就再次定时延期</span>
                        <span class="token comment">// reschedule itself</span>
                        <span class="token function">renewExpiration</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                        <span class="token function">cancelExpirationRenewal</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token comment">// 这里我们可以看到定时任务 是 lockWatchdogTimeout 的1/3时间去执行 renewExpirationAsync</span>
        <span class="token punctuation">}</span><span class="token punctuation">,</span> internalLockLeaseTime <span class="token operator">/</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

        ee<span class="token punctuation">.</span><span class="token function">setTimeout</span><span class="token punctuation">(</span>task<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
</code></pre></div><p><strong>最终通过Lua脚本实现延期</strong></p> <div class="language-lua extra-class"><pre class="language-lua"><code><span class="token operator">//</span> 延期锁的过期时间
<span class="token operator">//</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> 锁的名称
<span class="token operator">//</span> ARGV<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> 线程名称
<span class="token operator">//</span> ARGV<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> 过期时间
<span class="token keyword">if</span> <span class="token punctuation">(</span>redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'hexists'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">)</span>
  <span class="token keyword">then</span> redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">'pexpire'</span><span class="token punctuation">,</span> KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> ARGV<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token keyword">return</span> <span class="token number">1</span><span class="token punctuation">;</span> <span class="token keyword">end</span><span class="token punctuation">;</span> <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
</code></pre></div><p><strong>总结</strong></p> <ul><li><strong>watch dog</strong> 在当前节点存活时每10s给分布式锁的key续期 30s</li> <li><strong>watch dog</strong> 会每 <code>internalLockLeaseTime / 3</code> 时间，去延时, 所以可以通过 修改 <code>internalLockLeaseTime</code>  来实现延期策略</li> <li>要使用 <strong>watch dog</strong> 则 不要声明 过期时间</li> <li><strong>watch dog</strong> 机制启动，且代码中没有释放锁操作时，watch dog 会不断的给锁续期；</li> <li>建议还是将释放锁操作放在 <code>finally</code> 中</li></ul> <h2 id="相关文章"><a href="#相关文章" class="header-anchor">#</a> 相关文章</h2> <ul><li><a href="https://www.cnblogs.com/demingblog/p/9542124.html" target="_blank" rel="noopener noreferrer">Lua脚本在redis分布式锁场景的运用<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li> <li><a href="https://juejin.cn/post/6844903688088059912#heading-24" target="_blank" rel="noopener noreferrer">Redis实现分布式锁的7种方案，及正确使用姿势！<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li> <li><a href="https://juejin.cn/post/6854573212831842311" target="_blank" rel="noopener noreferrer">Redis——由分布式锁造成的重大事故<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li> <li><a href="https://juejin.cn/post/6844904191337431047#heading-3" target="_blank" rel="noopener noreferrer">介绍几种常见的分布式锁写法<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li> <li><a href="https://github.com/redisson/redisson/wiki/8.-%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E5%92%8C%E5%90%8C%E6%AD%A5%E5%99%A8#85-%E8%AF%BB%E5%86%99%E9%94%81readwritelock" target="_blank" rel="noopener noreferrer">Redisson wiki<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></section> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">上次更新: </span> <span class="time">4/21/2022, 8:17:59 AM</span></div></footer> <!----> <div class="comments-wrapper"><!----></div> <ul class="side-bar sub-sidebar-wrapper" style="width:12rem;" data-v-cb1513f6><li class="level-2" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#锁-和-分布式锁" class="sidebar-link reco-side-锁-和-分布式锁" data-v-cb1513f6>锁 和 分布式锁</a></li><li class="level-3" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#锁" class="sidebar-link reco-side-锁" data-v-cb1513f6>锁</a></li><li class="level-3" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#分布式锁" class="sidebar-link reco-side-分布式锁" data-v-cb1513f6>分布式锁</a></li><li class="level-2" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#锁的实现方式" class="sidebar-link reco-side-锁的实现方式" data-v-cb1513f6>锁的实现方式</a></li><li class="level-3" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#加锁" class="sidebar-link reco-side-加锁" data-v-cb1513f6>加锁</a></li><li class="level-3" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#解锁" class="sidebar-link reco-side-解锁" data-v-cb1513f6>解锁</a></li><li class="level-3" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#分布式环集群加锁" class="sidebar-link reco-side-分布式环集群加锁" data-v-cb1513f6>分布式环集群加锁</a></li><li class="level-3" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#分布式锁的安全问题" class="sidebar-link reco-side-分布式锁的安全问题" data-v-cb1513f6>分布式锁的安全问题</a></li><li class="level-2" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#redisson" class="sidebar-link reco-side-redisson" data-v-cb1513f6>Redisson</a></li><li class="level-3" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#如何实现的锁" class="sidebar-link reco-side-如何实现的锁" data-v-cb1513f6>如何实现的锁</a></li><li class="level-3" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#加锁-解锁过程分析" class="sidebar-link reco-side-加锁-解锁过程分析" data-v-cb1513f6>加锁&amp;解锁过程分析</a></li><li class="level-3" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#watch-dog" class="sidebar-link reco-side-watch-dog" data-v-cb1513f6>watch dog</a></li><li class="level-2" data-v-cb1513f6><a href="/oliver-vuepress/articles/middleware/redis/Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.html#相关文章" class="sidebar-link reco-side-相关文章" data-v-cb1513f6>相关文章</a></li></ul></main> <!----></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div></div></div>
    <script src="/oliver-vuepress/assets/js/app.c21e6ffc.js" defer></script><script src="/oliver-vuepress/assets/js/3.6dd9a2a1.js" defer></script><script src="/oliver-vuepress/assets/js/1.898920d0.js" defer></script><script src="/oliver-vuepress/assets/js/50.805e1466.js" defer></script>
  </body>
</html>
